package com.lyf.juc.practice.lock;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.*;

/**
 * @author LYF
 * @date 2022/6/23
 */
public class LockTests {
    Lock lock = new ReentrantLock();
    //Lock rwLock = new ReentrantReadWriteLock();
    final ReentrantReadWriteLock.WriteLock writeLock;
    final ReentrantReadWriteLock.ReadLock readLock;
    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();


    public LockTests(ReentrantReadWriteLock.WriteLock writeLock, ReentrantReadWriteLock.ReadLock readLock) {
        this.writeLock = writeLock;
        this.readLock = readLock;
    }


    @Test
    public void test1(){
        readWriteLock.readLock();
    }


    Condition notFull = lock.newCondition();
    Condition notEmpty = lock.newCondition();
    final int TOTAL = 10;
    List<Integer> list = new ArrayList<>(10);
    @Test
    public void test2(){
        AtomicInteger no = new AtomicInteger();
        // 生成者
        new Thread(()->{
            while (true){
                if(list.size()<TOTAL){
                    int random = new Random().nextInt(3);
                    //int randomNo = new Random().nextInt(10000);
                    try {
                        TimeUnit.SECONDS.sleep(random);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("生成产品-"+(no.getAndIncrement())+":花费时间"+random);
                    list.add(no.get());
                    notEmpty.signal();
                }
            }
        }).start();

        // 消费者
        new Thread(()->{
            while (true){
                if(list.size()>0){
                    int random = new Random().nextInt(3);
                    //int randomNo = new Random().nextInt(10000);
                    try {
                        TimeUnit.SECONDS.sleep(random);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    list.remove(list.size()-1);
                    notFull.signal();
                }
            }
        }).start();



    }




}
